//
//  TG_Vaildate.m
//  yunkaoqin
//
//  Created by 李丹 on 2019/5/23.
//  Copyright © 2019 lianzhituan. All rights reserved.
//

#import "TG_Vaildate.h"
#import <sys/stat.h>

#define myDotNumbers     @"0123456789.\n"
#define myNumbers          @"0123456789\n"

@implementation TG_Vaildate
/**
 *  判断密码是否是6位以上数字字母
 */
+(BOOL)judgePassWordLegal:(NSString *)pass{
    BOOL result = false;
    if ([pass length] >= 6){
        // 判断长度大于8位后再接着判断是否同时包含数字和字符
        NSString * regex = @"^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,16}$";
        NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
        result = [pred evaluateWithObject:pass];
    }
    return result;
}


+(BOOL)isIdCard:(NSString *)card {
    
    if ([self isHxIdentityCard:card]) {
        return YES;
    }else if ([self match:@"^[A-Z]{1,2}[0-9]{6}\\(?[0-9A]\\)?$" string:card]){
        return YES;
    }else if ([self match:@"^[1|5|7][0-9]{6}\([0-9Aa])" string:card]){
        return YES;
    }else if ([self match:@"[A-Z][0-9]{9}" string:card]){
        return YES;
    }
    else if ([self simpleVerifyIdentityCardNum:card]){
        return YES;
    }
    return NO;
    //    香港身份证正则表达式：
    //    var reg = /[A-Z]{1,2}[0-9]{6}([0-9A])/;
    //    澳门身份证正则表达式：
    //    var reg = /^[1|5|7][0-9]{6}\([0-9Aa]\)/;
    //    台湾身份证正则表达式：
    //    var reg = /[A-Z][0-9]{9}/;
    //
    
    
    
}
//身份证号
+ (BOOL) simpleVerifyIdentityCardNum:(NSString *)num
{
    NSString *regex2 = @"(^[0-9]{15}$)|([0-9]{17}([0-9]|X)$)";
    return [self match:regex2 string:num];
}
// 匹配身份证号码
+ (BOOL)isHxIdentityCard:(NSString *)card
{
    NSString *value = card;
    value = [value stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    
    int length =0;
    if (!value) {
        return NO;
    }else {
        length = (int)value.length;
        
        if (length !=15 && length !=18) {
            return NO;
        }
    }
    // 省份代码
    NSArray *areasArray =@[@"11",@"12", @"13",@"14", @"15",@"21", @"22",@"23", @"31",@"32", @"33",@"34", @"35",@"36", @"37",@"41", @"42",@"43", @"44",@"45", @"46",@"50", @"51",@"52", @"53",@"54", @"61",@"62", @"63",@"64", @"65",@"71", @"81",@"82", @"91"];
    
    NSString *valueStart2 = [value substringToIndex:2];
    BOOL areaFlag =NO;
    for (NSString *areaCode in areasArray) {
        if ([areaCode isEqualToString:valueStart2]) {
            areaFlag =YES;
            break;
        }
    }
    
    if (!areaFlag) {
        return false;
    }
    
    
    NSRegularExpression *regularExpression;
    NSUInteger numberofMatch;
    
    int year =0;
    switch (length) {
        case 15:
            year = [value substringWithRange:NSMakeRange(6,2)].intValue +1900;
            
            if (year %4 ==0 || (year %100 ==0 && year %4 ==0)) {
                
                regularExpression = [[NSRegularExpression alloc] initWithPattern:@"^[1-9][0-9]{5}[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|[1-2][0-9]))[0-9]{3}$"
                                                                         options:NSRegularExpressionCaseInsensitive
                                                                           error:nil];//测试出生日期的合法性
            }else {
                regularExpression = [[NSRegularExpression alloc]initWithPattern:@"^[1-9][0-9]{5}[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|1[0-9]|2[0-8]))[0-9]{3}$"
                                                                        options:NSRegularExpressionCaseInsensitive
                                                                          error:nil];//测试出生日期的合法性
            }
            numberofMatch = [regularExpression numberOfMatchesInString:value
                                                               options:NSMatchingReportProgress
                                                                 range:NSMakeRange(0, value.length)];
            
            if(numberofMatch >0) {
                return YES;
            }else {
                return NO;
            }
        case 18:
            year = [value substringWithRange:NSMakeRange(6,4)].intValue;
            if (year %4 ==0 || (year %100 ==0 && year %4 ==0)) {
                
                regularExpression = [[NSRegularExpression alloc] initWithPattern:@"^[1-9][0-9]{5}19[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|[1-2][0-9]))[0-9]{3}[0-9Xx]$"
                                                                         options:NSRegularExpressionCaseInsensitive
                                                                           error:nil];//测试出生日期的合法性
            }else {
                regularExpression = [[NSRegularExpression alloc] initWithPattern:@"^[1-9][0-9]{5}19[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|1[0-9]|2[0-8]))[0-9]{3}[0-9Xx]$"
                                                                         options:NSRegularExpressionCaseInsensitive
                                                                           error:nil];//测试出生日期的合法性
            }
            numberofMatch = [regularExpression numberOfMatchesInString:value
                                                               options:NSMatchingReportProgress
                                                                 range:NSMakeRange(0, value.length)];
            
            if(numberofMatch >0) {
                int S = ([value substringWithRange:NSMakeRange(0,1)].intValue + [value substringWithRange:NSMakeRange(10,1)].intValue) *7 + ([value substringWithRange:NSMakeRange(1,1)].intValue + [value substringWithRange:NSMakeRange(11,1)].intValue) *9 + ([value substringWithRange:NSMakeRange(2,1)].intValue + [value substringWithRange:NSMakeRange(12,1)].intValue) *10 + ([value substringWithRange:NSMakeRange(3,1)].intValue + [value substringWithRange:NSMakeRange(13,1)].intValue) *5 + ([value substringWithRange:NSMakeRange(4,1)].intValue + [value substringWithRange:NSMakeRange(14,1)].intValue) *8 + ([value substringWithRange:NSMakeRange(5,1)].intValue + [value substringWithRange:NSMakeRange(15,1)].intValue) *4 + ([value substringWithRange:NSMakeRange(6,1)].intValue + [value substringWithRange:NSMakeRange(16,1)].intValue) *2 + [value substringWithRange:NSMakeRange(7,1)].intValue *1 + [value substringWithRange:NSMakeRange(8,1)].intValue *6 + [value substringWithRange:NSMakeRange(9,1)].intValue *3;
                int Y = S %11;
                NSString *M =@"F";
                NSString *JYM =@"10X98765432";
                M = [JYM substringWithRange:NSMakeRange(Y,1)];// 判断校验位
                if ([M isEqualToString:[value substringWithRange:NSMakeRange(17,1)]]) {
                    return YES;// 检测ID的校验位
                }else {
                    return NO;
                }
                
            }else {
                return NO;
            }
        default:
            return NO;
    }
    
    
    //
    //    // 判断位数
    //    if ([self length] != 15 && [self length] != 18)
    //    {
    //        return NO;
    //    }
    //
    //    NSString *carid = [self uppercaseString];
    //    long lSumQT  =0;
    //    // 加权因子
    //    int R[] ={7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2 };
    //    // 校验码
    //    unsigned char sChecker[12]={'1','0','X', '9', '8', '7', '6', '5', '4', '3', '2'};
    //    // 将15位身份证号转换成18位
    //    NSMutableString *mString = [NSMutableString stringWithString:self];
    //    if ([self length] == 15)
    //    {
    //        [mString insertString:@"19" atIndex:6];
    //        long p = 0;
    //        const char *pid = [mString UTF8String];
    //        for (int i=0; i<=16; i++)
    //        {
    //            p += (pid[i]-48) * R[i];
    //        }
    //        int o = p%11;
    //        NSString *string_content = [NSString stringWithFormat:@"%c",sChecker[o]];
    //        [mString insertString:string_content atIndex:[mString length]];
    //        carid = mString;
    //    }
    //    // 判断地区码
    //    NSString * sProvince = [carid substringToIndex:2];
    //    if (![self areaCode:sProvince])
    //    {
    //        return NO;
    //    }
    //    // 判断年月日是否有效
    //    // 年份
    //    int strYear = [[carid substringWithRange:NSMakeRange(6,4)] intValue];
    //    // 月份
    //    int strMonth = [[carid substringWithRange:NSMakeRange(10,2)] intValue];
    //    // 日
    //    int strDay = [[carid substringWithRange:NSMakeRange(12,2)] intValue];
    //
    //    NSTimeZone *localZone = [NSTimeZone localTimeZone];
    //    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    //    [dateFormatter setDateStyle:NSDateFormatterMediumStyle];
    //    [dateFormatter setTimeStyle:NSDateFormatterNoStyle];
    //    [dateFormatter setTimeZone:localZone];
    //    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    //    NSDate *date=[dateFormatter dateFromString:[NSString stringWithFormat:@"%d-%d-%d 12:01:01",strYear,strMonth,strDay]];
    //    if (date == nil)
    //    {
    //        return NO;
    //    }
    //    const char *PaperId  = [carid UTF8String];
    //    // 检验长度
    //    if( 18 != strlen(PaperId)) return -1;
    //    // 校验数字
    //    for (int i=0; i<18; i++)
    //    {
    //        if ( !isdigit(PaperId[i]) && !(('X' == PaperId[i] || 'x' == PaperId[i]) && 17 == i) )
    //        {
    //            return NO;
    //        }
    //    }
    //    // 验证最末的校验码
    //    for (int i=0; i<=16; i++)
    //    {
    //        lSumQT += (PaperId[i]-48) * R[i];
    //    }
    //    if (sChecker[lSumQT%11] != PaperId[17] )
    //    {
    //        return NO;
    //    }
    //    return YES;
}

+ (BOOL)isPureInt:(NSString *)str{
    
    NSScanner *scan = [NSScanner scannerWithString:str];
    int val;
    return [scan scanInt:&val] && [scan isAtEnd];
}

+ (BOOL)validateByRegex:(NSString *)regex withObject:(id)object
{
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES% @", regex];
    return [predicate evaluateWithObject:object];
}

/**
 限制数字输入
 */
+(BOOL)isMatchNumFormat:(UITextField *)textField range:(NSRange)range string:(NSString *)string maxLength:(NSInteger)maxLength {
    if ([string isEqualToString:@"\n"]||[string isEqualToString:@""]) {//按下return
        return YES;
    }
    if(![self validateByRegex:@"[0-9]+" withObject:string]){
        return NO;
    }
    NSInteger length = maxLength>0 ? maxLength: 11;
    if (textField.text.length >= length) {
        return NO;
    }
    return YES;
}

/**
 禁止数字输入
 */
+(BOOL)isForbidNumFormat:(UITextField *)textField range:(NSRange)range string:(NSString *)string maxLength:(NSInteger)maxLength {
    if ([string isEqualToString:@"\n"]||[string isEqualToString:@""]) {//按下return
        return YES;
    }
    if([self validateByRegex:@"[0-9]+" withObject:string]){
        return NO;
    }
    NSInteger length = maxLength>0 ? maxLength: 11;
    if (textField.text.length >= length) {
        return NO;
    }
    return YES;
}

/**
 限制金额格式输入
 */
+(BOOL)isMatchMoneyFormat:(UITextField *)textField range:(NSRange)range string:(NSString *)string{
    
    if ([string isEqualToString:@"\n"]||[string isEqualToString:@""]) {//按下return
        return YES;
    }
    NSCharacterSet *cs;
    NSUInteger nDotLoc = [textField.text rangeOfString:@"."].location;
    if (NSNotFound == nDotLoc && 0 != range.location) {
        cs = [[NSCharacterSet characterSetWithCharactersInString:myNumbers]invertedSet];
        if ([string isEqualToString:@"."]) {
            return YES;
        }
        if (textField.text.length>=9) {  //小数点前面9位
            return NO;
        }
    }else {
        cs = [[NSCharacterSet characterSetWithCharactersInString:myDotNumbers]invertedSet];
        if (textField.text.length>=12) {
            return  NO;
        }
    }
    //当没有输入其他时,不允许输入小数点
    if([textField.text isEqualToString:@""] && [string isEqualToString:@"."]){
        return NO;
    }
    //只允许有一个小数点
    if([textField.text rangeOfString:@"."].location != NSNotFound && [string isEqualToString:@"."]) {
        return NO;
    }
    NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];
    BOOL basicTest = [string isEqualToString:filtered];
    if (!basicTest) {
        return NO;
    }
    if (NSNotFound != nDotLoc && range.location > nDotLoc +2) {//小数点后面两位
        return NO;
    }
    return YES;
}

/**
 限制小时数格式输入
 */
+(BOOL)isMatchHourFormat:(UITextField *)textField range:(NSRange)range string:(NSString *)string{
    
    if ([string isEqualToString:@"\n"]||[string isEqualToString:@""]) {//按下return
        return YES;
    }
    NSCharacterSet *cs;
    NSUInteger nDotLoc = [textField.text rangeOfString:@"."].location;
    if (NSNotFound == nDotLoc && 0 != range.location) {
        cs = [[NSCharacterSet characterSetWithCharactersInString:myNumbers]invertedSet];
        if ([string isEqualToString:@"."]) {
            return YES;
        }
        if (textField.text.length>=9) {  //小数点前面9位
            return NO;
        }
    }else {
        cs = [[NSCharacterSet characterSetWithCharactersInString:myDotNumbers]invertedSet];
        if (textField.text.length>=11) {
            return  NO;
        }
    }
    //当没有输入其他时,不允许输入小数点
    if([textField.text isEqualToString:@""] && [string isEqualToString:@"."]){
        return NO;
    }
    //只允许有一个小数点
    if([textField.text rangeOfString:@"."].location != NSNotFound && [string isEqualToString:@"."]) {
        return NO;
    }
    NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];
    BOOL basicTest = [string isEqualToString:filtered];
    if (!basicTest) {
        return NO;
    }
    if (NSNotFound != nDotLoc && range.location > nDotLoc +1) {//小数点后面一位
        return NO;
    }
    return YES;
}

/**
 限制身份证输入
 */
+ (BOOL)isMatchIdCardFormat:(UITextField *)textField range:(NSRange)range string:(NSString *)strin {
    if ([strin isEqualToString:@"\n"]||[strin isEqualToString:@""]) {//按下return
        return YES;
    }
    NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:@"0123456789Xx"] invertedSet];
    NSString *filtered = [[strin componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];
    BOOL result = [strin isEqualToString:filtered];
    return result;
}

/**
 限制中文输入
 */
+ (BOOL)isMatchChineseFormat:(UITextField *)textField range:(NSRange)range string:(NSString *)strin {
    if ([strin isEqualToString:@"\n"]||[strin isEqualToString:@""]) {//按下return
        return YES;
    }
    NSString *regex = @"[\u4e00-\u9fa5]{0,}";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    BOOL isMatch = [pred evaluateWithObject:strin];
    if(isMatch==0){
        return NO;
    }
    return YES;
}

+ (BOOL)isPureLetter:(NSString *)str{
    if (str.length == 0) return NO;
    NSString *regex =@"[a-zA-Z]*";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex];
    return [pred evaluateWithObject:str];
}

+ (BOOL)isMatchNumberWordChinese:(NSString *)str{
    NSString *regex = @"[a-zA-Z0-9\u4e00-\u9fa5][a-zA-Z0-9\u4e00-\u9fa5]+";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    BOOL isMatch = [pred evaluateWithObject:str];
    if(isMatch==0){
        return NO;
    }
    return YES;
}

+ (NSString *)replaceChineseWithEmptyChar:(NSString *)str {
    NSMutableString *tempMStr = [NSMutableString string];
    for(int i=0; i< [str length];i++){
        int a = [str characterAtIndex:i];
        NSString *subStr = [str substringWithRange:NSMakeRange(i, 1)];
        if( a > 0x4e00 && a < 0x9fff) {
            [tempMStr appendString:@""];
        } else if ([self isPureInt:subStr] || [self isPureLetter:subStr]) {
            [tempMStr appendString:subStr];
        }
        NSLog(@"--- %@", tempMStr);
    }
    return tempMStr.uppercaseString;
}

+ (BOOL)hasChinese:(NSString *)str{
    for(int i=0; i< [str length];i++){
        int a = [str characterAtIndex:i];
        if( a > 0x4e00 && a < 0x9fff)
        {
            return YES;
        }
    }
    return NO;
}

+ (BOOL)isJailBreak{
#if TARGET_IPHONE_SIMULATOR
    return false;
#elif TARGET_OS_IPHONE
#endif
    
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wunreachable-code"
    //判断这些文件是否存在，只要有存在的，就可以认为手机已经越狱了。
    NSArray *jailbreak_tool_paths = @[
                                      @"/Applications/Cydia.app",
                                      @"/Library/MobileSubstrate/MobileSubstrate.dylib",
                                      @"/bin/bash",
                                      @"/usr/sbin/sshd",
                                      @"/etc/apt"
                                      ];
    for (int i=0; i<jailbreak_tool_paths.count; i++) {
        if ([[NSFileManager defaultManager] fileExistsAtPath:jailbreak_tool_paths[i]]) {
            NSLog(@"The device is jail broken!");
            return YES;
        }
    }
    
    //根据是否能打开cydia判断
    //    if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"cydia://"]]) {
    //        NSLog(@"The device is jail broken!");
    //        return YES;
    //    }
    
    //根据是否能获取所有应用的名称判断
    if ([[NSFileManager defaultManager] fileExistsAtPath:@"User/Applications/"]) {
        NSLog(@"The device is jail broken!");
        NSArray *appList = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:@"User/Applications/" error:nil];
        NSLog(@"appList = %@", appList);
        return YES;
    }
    
    struct stat stat_info;
    if (0 == stat("/Applications/Cydia.app", &stat_info)) {
        exit(0);
    }
    
    return NO;
#pragma clang diagnostic pop
}
+(BOOL)isVideo:(NSString *)url
{
    if (url == nil) {
        return NO;
    }
    NSString *path = url.pathExtension;
    if ([path isEqualToString:@"mp4"]||[path isEqualToString:@"MP4"]||[path isEqualToString:@"MPEG-4"]
        ||[path isEqualToString:@"MOV"]||[path isEqualToString:@"avi"]) {
        return YES;
    }
    return NO;;
}

+ (BOOL)isInstallFromAppStore{
    //只要判断embedded.mobileprovision文件存在 AppStore下载的是不包含的
    NSString *mobileProvisionPath = [[NSBundle mainBundle] pathForResource:@"embedded" ofType:@"mobileprovision"];
    if (mobileProvisionPath) {
        return NO;
    }
    return YES;
}

/** 传入一个规则，判断自己是否符合这个规则*/
+(BOOL)match:(NSString *)pattern string:(NSString *)string{
    
    NSPredicate *prediate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",pattern];
    
    return [prediate evaluateWithObject:string];
}
// 手机号码验证
+ (BOOL)validateMobile:(NSString *)mobileStr{
    return [self match:@"^1[23456789]{1}\\d{9}$" string:mobileStr];
}

//邮箱
+ (BOOL)validateEmail:(NSString *)emailStr{
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    return [emailTest evaluateWithObject:emailStr];
}
/**
 *  字符是否是空
 */
+(BOOL)isEmptyString:(NSString*)string
{
    if (string == nil) {
        return YES;
    }
    if (!string || [string isKindOfClass:[NSNull class]] ||string == 0||
        [[StringChar(string) stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] length]==0) {
        return YES;
    }
    return NO;
}
+(BOOL)isURLPrefix:(NSString*)string{
    if (!string) {
        return NO;
    }
    if (![string isKindOfClass:[NSString class]]) {
        return NO;
    }
    if ([string hasPrefix:@"http"]||[string hasPrefix:@"https"]||[string hasPrefix:@"ftp"]
        || [string containsString:@"click.taobao.com"] || [string containsString:@"s.click.ele"]) {
        return YES;
    }
    return NO;
}
+ (BOOL) checkCardNo:(NSString*) cardNo{
    if (cardNo==nil) {
        return NO;
        
    }
    int oddsum = 0;     //奇数求和
    int evensum = 0;    //偶数求和
    int allsum = 0;
    int cardNoLength = (int)[cardNo length];
    int lastNum = [[cardNo substringFromIndex:cardNoLength-1] intValue];
    
    cardNo = [cardNo substringToIndex:cardNoLength - 1];
    for (int i = cardNoLength -1 ; i>=1;i--) {
        NSString *tmpString = [cardNo substringWithRange:NSMakeRange(i-1, 1)];
        int tmpVal = [tmpString intValue];
        if (cardNoLength % 2 ==1 ) {
            if((i % 2) == 0){
                tmpVal *= 2;
                if(tmpVal>=10)
                    tmpVal -= 9;
                evensum += tmpVal;
            }else{
                oddsum += tmpVal;
            }
        }else{
            if((i % 2) == 1){
                tmpVal *= 2;
                if(tmpVal>=10)
                    tmpVal -= 9;
                evensum += tmpVal;
            }else{
                oddsum += tmpVal;
            }
        }
    }
    
    allsum = oddsum + evensum;
    allsum += lastNum;
    if((allsum % 10) == 0)
        return YES;
    else
        return NO;
}
+ (BOOL) checkCarNumber:(NSString *)number{
    NSString *CarkNum = @"([京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[A-Z]{1}(([0-9]{5}[DF])|([DF]([A-HJ-NP-Z0-9])[0-9]{4})))|([京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[A-Z]{1}[A-HJ-NP-Z0-9]{4}[A-HJ-NP-Z0-9挂学警港澳]{1})";
    //    NSString *CarkNum = @"^[\u4e00-\u9fa5]{1}[a-zA-Z]{1}[a-zA-Z_0-9]{4}[a-zA-Z_0-9_\u4e00-\u9fa5]$";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",CarkNum];
    BOOL isMatch = [pred evaluateWithObject:number];
    return isMatch;
}
+(BOOL)verifyVIN:(NSString *)vin {
    // 先用正则过滤 (只能包含0-9  A-H,J-N,P,R-Z 且必须为17位)
    NSString *vinRegex = @"^[A-HJ-NPR-Z0-9]{0,17}$";
    NSPredicate *vinTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", vinRegex];
    if(![vinTest evaluateWithObject:vin] || vin.length != 17) {
        return NO;
    }
    
    NSDictionary *alphabetDict = @{@"A":@1,
                                   @"B":@2,
                                   @"C":@3,
                                   @"D":@4,
                                   @"E":@5,
                                   @"F":@6,
                                   @"G":@7,
                                   @"H":@8,
                                   @"J":@1,
                                   @"K":@2,
                                   @"L":@3,
                                   @"M":@4,
                                   @"N":@5,
                                   @"P":@7,
                                   @"R":@9,
                                   @"S":@2,
                                   @"T":@3,
                                   @"U":@4,
                                   @"V":@5,
                                   @"W":@6,
                                   @"X":@7,
                                   @"Y":@8,
                                   @"Z":@9,
                                   };
    NSArray *weightArray = @[@8,@7,@6,@5,@4,@3,@2,@10,@0,@9,@8,@7,@6,@5,@4,@3,@2];
    
    NSInteger sum  = 0;
    for (NSInteger i = 0 ; i < 17; i++) {
        if (i == 8) { // 第九位不计入sum
            continue;
        }
        unichar indexChar = [vin characterAtIndex:i];
        NSString *indexString = [NSString stringWithCharacters:&indexChar length:1];
        NSCharacterSet *letters = [NSCharacterSet letterCharacterSet];
        if ([letters characterIsMember:indexChar]) { // 字母
            indexString = [indexString uppercaseString]; // 转为大写
            NSNumber *valueNum = alphabetDict[indexString];
            sum += valueNum.integerValue * [weightArray[i] integerValue];
        }else { // 数字
            sum += indexString.integerValue * [weightArray[i] integerValue];
        }
    }
    
    unichar nineChar = [vin characterAtIndex:8];
    NSString *nineString = [NSString stringWithCharacters:&nineChar length:1];
    NSCharacterSet *letters = [NSCharacterSet letterCharacterSet];
    if ([letters characterIsMember:nineChar]) {
        nineString = [nineString uppercaseString];
        if ([nineString isEqualToString:@"X"]) {
            nineString = @"10";
        }
    }
    if (sum % 11 == nineString.integerValue) {
        return YES;
    }else{
        return NO;
    }
}

@end
